package com.alibaba.algo.core.base;

import com.alibaba.algo.util.DateConverterUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: glorysongglory
 * Date: 2020/5/9
 * Time: 9:06
 */
public class BaseDomain<T extends BaseEntity> {

    @Autowired
    protected BaseMapper<T> mapper;

    public int insert(T entity) {
        entity.setId(0L);
        LocalDateTime cutDateTime = DateConverterUtils.asLocalDateTime(new Date());
        entity.setGmtCreated(cutDateTime);
        entity.setGmtModified(cutDateTime);
        entity.setIsDeleted(YesOrNo.N.name());
        return mapper.insert(entity);
    }

    public int insertWithID(T entity) {
        LocalDateTime cutDateTime = DateConverterUtils.asLocalDateTime(new Date());
        entity.setGmtCreated(cutDateTime);
        entity.setGmtModified(cutDateTime);
        entity.setIsDeleted(YesOrNo.N.name());
        return mapper.insert(entity);
    }

    public int updateById(T entity) {
        return mapper.updateById(entity);
    }

    public T getById(Long id) {
        return mapper.getById(id);
    }

    public Integer countByPara(T entity) {
        return mapper.countByPara(entity);
    }

    public List<T> listByPara(T entity, LinkedHashMap<String, Object> sortMap) {
        return mapper.listByPara(entity, CoreTools.getSortStr(sortMap));
    }

    public List<T> listByParaStrSort(T entity, String strSort) {
        return mapper.listByPara(entity, strSort);
    }

    public PagerEntity pageByPara(T entity, Integer pageIndex, Integer pageSize, LinkedHashMap<String, Object> sortMap) {
        long total = mapper.countByPara(entity);
        Pager pager = Pager.newInstance(total, pageIndex, pageSize);
        List<T> result = mapper.pageByPara(entity, pager.getStart(), pager.getEnd(), CoreTools.getSortStr(sortMap));
        return new PagerEntity(total, pager.getTotalPages(), pageSize, pageIndex, result);
    }

}
